# 模型状态监控模块
import time
from typing import Dict, List

class ModelStatus:
    def __init__(self):
        self.status = {
            'xinghe': {
                'available': True,
                'last_check': time.time(),
                'error_count': 0,
                'model': 'ernie-bot-turbo'
            },
            'openai': {
                'available': True,
                'last_check': time.time(),
                'error_count': 0,
                'model': 'gpt-3.5-turbo'
            },
            'deepseek': {
                'available': True,
                'last_check': time.time(),
                'error_count': 0,
                'model': 'deepseek-chat'
            },
            'fallback': {
                'available': True,
                'last_check': time.time(),
                'error_count': 0,
                'model': 'local-fallback'
            }
        }
        self.current_model = 'xinghe'
    
    def update_status(self, model: str, success: bool, error_message: str = None):
        """更新模型状态"""
        if model in self.status:
            self.status[model]['last_check'] = time.time()
            if success:
                self.status[model]['available'] = True
                self.status[model]['error_count'] = 0
            else:
                self.status[model]['error_count'] += 1
                if self.status[model]['error_count'] >= 3:
                    self.status[model]['available'] = False
    
    def get_available_models(self) -> List[str]:
        """获取可用的模型列表"""
        return [model for model, info in self.status.items() if info['available']]
    
    def get_current_model(self) -> str:
        """获取当前使用的模型"""
        return self.current_model
    
    def switch_model(self, model: str):
        """切换模型"""
        if model in self.status and self.status[model]['available']:
            self.current_model = model
            return True
        return False
    
    def get_status_summary(self) -> Dict:
        """获取状态摘要"""
        return {
            'current_model': self.current_model,
            'available_models': self.get_available_models(),
            'status': self.status
        }
    
    def reset_status(self):
        """重置所有模型状态"""
        for model in self.status:
            self.status[model]['available'] = True
            self.status[model]['error_count'] = 0
            self.status[model]['last_check'] = time.time()
        self.current_model = 'xinghe'

# 全局状态实例
model_status = ModelStatus() 